home *** CD-ROM | disk | FTP | other *** search
/ Digital Information Mana…ntial Guide to Multimedia / Digital Information Management - An Essential Guide to Multimedia.iso / Audacity / Nyquist / nyquist.lsp < prev    next >
Lisp/Scheme  |  2006-05-16  |  49KB  |  1,536 lines

  1. ;;;
  2. ;;;   ###########################################################
  3. ;;;   ### NYQUIST-- A Language for Composition and Synthesis. ###
  4. ;;;   ###                                                     ###
  5. ;;;   ### Copyright (c) 1994 by Roger B. Dannenberg           ###
  6. ;;;   ###########################################################
  7. ;;;
  8.  
  9. ;;;   
  10. ;;;   Modifications for using Nyquist within Audacity
  11. ;;;   by Dominic Mazzoni
  12. ;;;
  13.  
  14. (prog ()
  15.    (setq lppp -12.0) (setq lpp -9.0)  (setq lp -6.0)    (setq lmp -3.0)
  16.    (setq lfff 12.0) (setq lff 9.0)  (setq lf 6.0)    (setq lmf 3.0)
  17.    (setq dB0 1.00)  (setq dB1 1.122) (setq dB10 3.1623)
  18.  
  19.    (setq s 0.25) (setq sd 0.375) (setq st (/ 0.5 3.0))
  20.    (setq i 0.5)  (setq id 0.75)  (setq it (* st 2.0))
  21.    (setq q 1.0)  (setq qd 1.5)   (setq qt (* st 4.0))
  22.    (setq h 2.0)  (setq hd 3.0)   (setq ht (* st 8.0))
  23.    (setq w 4.0)  (setq wd 6.0)   (setq wt (* st 16.0))
  24. )
  25.  
  26. (if (not (boundp '*A4-Hertz*))
  27.     (setf *A4-Hertz* 440.0))
  28.  
  29. ; next pitch, for initializations below
  30. (defun np () (incf nyq:next-pitch))
  31.  
  32. (defun set-pitch-names ()
  33.    (setq no-pitch 116.0)
  34.    ; note: 58.0 is A4 - (C0 - 1) = 69 - (12 - 1)
  35.    (setf nyq:next-pitch (- (hz-to-step *A4-Hertz*) 58.0))
  36.  
  37.    (setf nyq:pitch-names
  38.     '(c0 (cs0 df0) d0 (ds0 ef0) e0 f0 (fs0 gf0) g0 (gs0 af0) a0
  39.       (as0 bf0) b0
  40.       c1 (cs1 df1) d1 (ds1 ef1) e1 f1 (fs1 gf1) g1 (gs1 af1) a1
  41.       (as1 bf1) b1
  42.       c2 (cs2 df2) d2 (ds2 ef2) e2 f2 (fs2 gf2) g2 (gs2 af2) a2
  43.       (as2 bf2) b2
  44.       c3 (cs3 df3) d3 (ds3 ef3) e3 f3 (fs3 gf3) g3 (gs3 af3) a3
  45.       (as3 bf3) b3
  46.       c4 (cs4 df4) d4 (ds4 ef4) e4 f4 (fs4 gf4) g4 (gs4 af4) a4
  47.       (as4 bf4) b4
  48.       c5 (cs5 df5) d5 (ds5 ef5) e5 f5 (fs5 gf5) g5 (gs5 af5) a5
  49.       (as5 bf5) b5
  50.       c6 (cs6 df6) d6 (ds6 ef6) e6 f6 (fs6 gf6) g6 (gs6 af6) a6
  51.       (as6 bf6) b6
  52.       c7 (cs7 df7) d7 (ds7 ef7) e7 f7 (fs7 gf7) g7 (gs7 af7) a7
  53.       (as7 bf7) b7))
  54.  
  55.    (dolist (p nyq:pitch-names)
  56.      (cond ((atom p) (set p (np)))
  57.        (t (let ((pitch (np)))
  58.         (dolist (s p) (set s pitch)))))))
  59.  
  60.  
  61. (set-pitch-names)
  62.  
  63. (if (not (boundp '*DEFAULT-SOUND-SRATE*))
  64.   (setf *DEFAULT-SOUND-SRATE* 44100.0))
  65. (if (not (boundp '*DEFAULT-CONTROL-SRATE*))
  66.   (setf *DEFAULT-CONTROL-SRATE* 2205.0))
  67.  
  68. (setf *environment-variables*
  69.       '(*WARP* *SUSTAIN* *START* *LOUD* *TRANSPOSE* 
  70.     *STOP* *CONTROL-SRATE* *SOUND-SRATE*))
  71.  
  72. (setfn environment-time car)
  73. (setfn environment-stretch cadr)
  74.  
  75. ; ENVIRONMENT-MAP - map virtual time using an environment
  76. ;
  77. ;(defun environment-map (env tim)
  78. ;  (+ (environment-time env)
  79. ;     (* (environment-stretch env) tim)))
  80.  
  81.  
  82. (defun nyq:the-environment () (mapcar 'eval *environment-variables*))
  83.  
  84.  
  85. ;; GLOBAL ENVIRONMENT VARIABLES and their startup values:
  86. (defun nyq:environment-init ()
  87.   (setq *WARP*        '(0.0 1.0 nil))
  88.   (setq *LOUD*    0.0)   ; now in dB
  89.   (setq *TRANSPOSE*    0.0)
  90.   (setq *SUSTAIN*            1.0)
  91.   (setq *START*       MIN-START-TIME)
  92.   (setq *STOP*        MAX-STOP-TIME)
  93.   (setq *CONTROL-SRATE*  *DEFAULT-CONTROL-SRATE*)
  94.   (setq *SOUND-SRATE* *DEFAULT-SOUND-SRATE*)
  95.   t)                ; return nothing in particular
  96.  
  97. (nyq:environment-init)
  98.  
  99. (defun get-duration (dur)
  100.   (- (local-to-global (* (get-sustain) dur))
  101.      (setf *rslt* (local-to-global 0))))
  102.  
  103.  
  104. (defun get-loud ()
  105.   (cond ((numberp *loud*) *loud*)
  106.     ((soundp *loud*)
  107.      (sref *loud* 0))
  108.     (t
  109.      (error (format t "*LOUD* should be a number or sound: ~A" *LOUD*)))))
  110.  
  111.  
  112. (defun get-sustain ()
  113.   (cond ((numberp *SUSTAIN*) *SUSTAIN*)
  114.     ((soundp *SUSTAIN*)
  115.      ;(display "get-sustain: lookup " (local-to-global 0) 0))
  116.      (sref *SUSTAIN* 0))
  117.     (t
  118.      (error (format t "*SUSTAIN* should be a number or sound: ~A" *SUSTAIN*)))))
  119.  
  120.  
  121. (defun get-tempo ()
  122.   (slope (snd-inverse (get-warp) (local-to-global 0)
  123.               *control-srate*)))
  124.  
  125. (defun get-transpose ()
  126.   (cond ((numberp *TRANSPOSE*) *TRANSPOSE*)
  127.     ((soundp *TRANSPOSE*)
  128.      ; (display "get-transpose: lookup " 0)
  129.      ; (format t "samples: ~A~%" (snd-samples *TRANSPOSE* 100))
  130.      (sref *TRANSPOSE* 0))
  131.     (t
  132.      (error (format t "*TRANSPOSE* should be a number or sound: ~A" *TRANSPOSE*)))))
  133.  
  134.  
  135. (defun get-warp ()
  136.   (let ((f (warp-function *WARP*)))
  137.     (cond ((null f) (error "Null warp function"))
  138.     (t
  139.      (shift-time (scale-srate f (/ (warp-stretch *WARP*)))
  140.              (- (warp-time *WARP*)))))))
  141.  
  142.  
  143. ;;;;;;;;;;;;;;;;;;;;;;
  144. ;; OSCILATORS
  145. ;;;;;;;;;;;;;;;;;;;;;;
  146.  
  147. (defun build-harmonic (n table-size) (snd-sine 0 n table-size 1))
  148.  
  149. (setf *SINE-TABLE* (list (build-harmonic 1 2048)
  150.              (hz-to-step 1.0)
  151.              T))
  152. (setf *TABLE* *SINE-TABLE*)
  153.  
  154.  
  155. ;; AMOSC
  156. ;;
  157. (defun amosc (pitch modulation &optional (sound *table*) (phase 0.0))
  158.   (let ((modulation-srate (snd-srate modulation))
  159.     (hz (step-to-hz (+ pitch (get-transpose)))))
  160.     (cond ((> *SOUND-SRATE* modulation-srate)
  161.        (setf modulation (snd-up *SOUND-SRATE* modulation)))
  162.       ((< *SOUND-SRATE* modulation-srate)
  163.        (format t "Warning: down-sampling AM modulation in amosc~%")
  164.        (setf modulation (snd-down *SOUND-SRATE* modulation))))
  165.     (cond ((> hz (/ *SOUND-SRATE* 2))
  166.        (format t "Warning: amosc frequency (~A hz) will alias at current sample rate (~A hz).\n"
  167.            hz *SOUND-SRATE*)))
  168.     (scale-db (get-loud)
  169.       (snd-amosc
  170.     (car sound)    ; samples for table
  171.     (cadr sound)    ; step represented by table
  172.     *SOUND-SRATE*    ; output sample rate
  173.     hz        ;  output hz
  174.     (local-to-global 0)    ; starting time
  175.     modulation    ; modulation
  176.     phase))))    ; phase
  177.  
  178.  
  179. ;; FMOSC
  180. ;;
  181. ;; modulation rate must be less than or equal to sound-srate, so
  182. ;; force resampling and issue a warning if necessary. snd-fmosc can
  183. ;; handle upsampling cases internally.
  184. ;;
  185. (defun fmosc (pitch modulation &optional (sound *table*) (phase 0.0))
  186.   (let ((modulation-srate (snd-srate modulation))
  187.         (hz (step-to-hz (+ pitch (get-transpose)))))
  188.     (cond ((< *SOUND-SRATE* modulation-srate)
  189.        (format t "Warning: down-sampling FM modulation in fmosc~%")
  190.        (setf modulation (snd-down *SOUND-SRATE* modulation))))
  191.     (cond ((> hz (/ *SOUND-SRATE* 2))
  192.        (format t "Warning: fmosc nominal frequency (~A hz) will alias at current sample rate (~A hz).\n"
  193.            hz *SOUND-SRATE*)))
  194.     (scale-db (get-loud)
  195.       (snd-fmosc 
  196.         (car sound)        ; samples for table
  197.         (cadr sound)        ; step represented by table
  198.         *SOUND-SRATE*        ; output sample rate
  199.         hz            ;  output hz
  200.         (local-to-global 0)    ; starting time
  201.         modulation        ; modulation
  202.         phase))))        ; phase
  203.  
  204.  
  205. ;; BUZZ
  206. ;;
  207. ;; (ARGUMENTS ("long" "n") ("rate_type" "sr") ("double" "hz")
  208. ;;            ("time_type" "t0") ("sound_type" "s_fm"))
  209. ;; 
  210. (defun buzz (n pitch modulation)
  211.   (let ((modulation-srate (snd-srate modulation))
  212.         (hz (step-to-hz (+ pitch (get-transpose)))))
  213.     (cond ((< *SOUND-SRATE* modulation-srate)
  214.            (format t "Warning: down-sampling modulation in buzz~%")
  215.            (setf modulation (snd-down *SOUND-SRATE* modulation))))
  216.     (cond ((> hz (/ *SOUND-SRATE* 2))
  217.            (format t "Warning: buzz nominal frequency (~A hz) will alias at current sample rate (~A hz).\n"
  218.                    hz *SOUND-SRATE*)))
  219.     (setf n (min n 1)) ; avoid divide by zero problem
  220.     (scale-db (get-loud)
  221.               (snd-buzz n                   ; number of harmonics
  222.                         *SOUND-SRATE*       ; output sample rate
  223.                         hz                  ; output hz
  224.                         (local-to-global 0) ; starting time
  225.                         modulation))))      ; freq. modulation
  226.                         
  227.  
  228. ;; (HZOSC hz [table [phase]])
  229. ;;
  230. ;; similar to FMOSC, but without "carrier" frequency parameter
  231. ;; also, hz may be a scalar or a sound
  232. ;;
  233. (defun hzosc (hz &optional (sound *table*) (phase 0.0))
  234.   (let (hz-srate)
  235.     (cond ((numberp hz)
  236.            (osc (hz-to-step hz) 1.0 sound phase))
  237.           (t
  238.            (setf hz-srate (snd-srate hz))
  239.            (cond ((< *SOUND-SRATE* hz-srate)
  240.                   (format t "Warning: down-sampling hz in hzosc~%")
  241.                   (setf hz (snd-down *SOUND-SRATE* hz))))
  242.            (scale-db (get-loud)
  243.                      (snd-fmosc (car sound) ; samples for table
  244.                                 (cadr sound) ; step repr. by table
  245.                                 *SOUND-SRATE* ; output sample rate
  246.                                 0.0 ; dummy carrier
  247.                                 (local-to-global 0) ; starting time
  248.                                 hz phase))))))
  249.  
  250.  
  251. ;; (SIOSC-BREAKPOINTS tab0 t1 tab1 ... tn tabn)
  252. ;;   converts times to sample numbers
  253. ;; NOTE: time-warping the spectral envelope seems
  254. ;; like the wrong thing to do (wouldn't it be better
  255. ;; to warp the parameters that control the spectra,
  256. ;; or don't warp at all?). Nominally, a note should
  257. ;; have a "score" or local time duration equal to the
  258. ;; SUSTAIN environment variable. (When sustain is 1.0
  259. ;; and no time-warping is in effect, the duration is 1).
  260. ;; So, scale all times by
  261. ;;        (local-to-global (get-sustain))
  262. ;; so that if the final time tn = 1.0, we get a nominal
  263. ;; length note.
  264.  
  265. (defun siosc-breakpoints (breakpoints)
  266.   (display "siosc-breakpoints" breakpoints)
  267.   (prog (sample-count result (last-count 0) time-factor)
  268.     (setf time-factor
  269.       (- (local-to-global (get-sustain))
  270.          (local-to-global 0.0)))
  271.     (setf time-factor (* time-factor *SOUND-SRATE*))
  272.     (cond ((and (listp breakpoints)
  273.         (cdr breakpoints)
  274.         (cddr breakpoints)))
  275.       (t (error "SIOSC table list must have at least 3 elements")))
  276. loop
  277.     (cond ((and (listp breakpoints)
  278.            (soundp (car breakpoints)))
  279.        (push (car breakpoints) result)
  280.        (setf breakpoints (cdr breakpoints)))
  281.       (t
  282.        (error "SIOSC expecting SOUND in table list")))
  283.     (cond ((and breakpoints
  284.         (listp breakpoints)
  285.         (numberp (car breakpoints)))
  286.        (setf sample-count (truncate
  287.         (+ 0.5 (* time-factor (car breakpoints)))))
  288.        (cond ((< sample-count last-count)
  289.           (setf sample-count (1+ last-count))))
  290.        (push sample-count result)
  291.        (setf last-count sample-count)
  292.        (setf breakpoints (cdr breakpoints))
  293.        (cond (breakpoints
  294.           (go loop))))
  295.       (breakpoints
  296.        (error "SIOSC expecting number (time) in table list")))
  297.     (setf result (reverse result))
  298.     (display "siosc-breakpoints" result)
  299.     (return result)))
  300.  
  301. ;; SIOSC -- spectral interpolation oscillator
  302. ;;
  303. ;; modulation rate must be less than or equal to sound-srate, so
  304. ;; force resampling and issue a warning if necessary. snd-fmosc can
  305. ;; handle upsampling cases internally.
  306. ;;
  307. (defun siosc (pitch modulation breakpoints)
  308.   (let ((modulation-srate (snd-srate modulation))
  309.     (hz (step-to-hz (+ pitch (get-transpose)))))
  310.     (cond ((< *SOUND-SRATE* modulation-srate)
  311.        (format t "Warning: down-sampling FM modulation in siosc~%")
  312.        (setf modulation (snd-down *SOUND-SRATE* modulation))))
  313.     (cond ((> hz (/ *SOUND-SRATE* 2))
  314.        (format t "Warning: siosc nominal frequency (~A hz) will alias at current sample rate (~A hz).\n"
  315.            hz *SOUND-SRATE*)))
  316.      (scale-db (get-loud)
  317.       (snd-siosc 
  318.     (siosc-breakpoints breakpoints)    ; tables
  319.     *SOUND-SRATE*        ; output sample rate
  320.     hz            ;  output hz
  321.     (local-to-global 0)    ; starting time
  322.     modulation))))        ; modulation
  323.  
  324.  
  325. ;; LFO -- freq &optional duration sound phase)
  326. ;;
  327. ;; Default duration is 1.0 sec, default sound is *TABLE*, 
  328. ;; default phase is 0.0.
  329. ;;
  330. (defun lfo (freq &optional (duration 1.0)
  331.          (sound *SINE-TABLE*) (phase 0.0))
  332.   (let ((d (get-duration duration)))
  333.     (if (minusp d) (setf d 0))
  334.     (cond ((> freq (/ *CONTROL-SRATE* 2))
  335.        (format t "Warning: lfo frequency (~A hz) will alias at current control rate (~A hz).\n"
  336.            freq *CONTROL-SRATE*)))
  337.      (snd-osc
  338.     (car sound)        ; samples for table
  339.     (cadr sound)        ; step represented by table
  340.     *CONTROL-SRATE*        ; output sample rate
  341.     freq            ; output hz
  342.     *rslt*            ; starting time
  343.     d            ; duration
  344.     phase)))        ; phase
  345.  
  346. ;; FMLFO -- like LFO but uses frequency modulation
  347. ;;
  348. (defun fmlfo (freq &optional (sound *SINE-TABLE*) (phase 0.0))
  349.   (let ()
  350.     (cond ((numberp freq)
  351.            (lfo freq 1.0 sound phase))
  352.           ((soundp freq)
  353.            (cond ((> (snd-srate freq) *CONTROL-SRATE*)
  354.                   (setf freq (force-srate *CONTROL-SRATE* freq))))
  355.            (snd-fmosc (car sound) (cadr sound) *CONTROL-SRATE* 0.0 
  356.                       (local-to-global 0) freq phase))
  357.           (t
  358.            (error "frequency must be a number or sound")))))
  359.  
  360. ;; OSC - table lookup oscillator
  361. ;;
  362. (defun osc (pitch &optional (duration 1.0) 
  363.           (sound *TABLE*) (phase 0.0))
  364.   (let ((d (get-duration duration))
  365.     (hz (step-to-hz (+ pitch (get-transpose)))))
  366.     ;(display "osc" *warp* global-start global-stop actual-dur  
  367.     ;         (get-transpose))
  368.     (cond ((> hz (/ *SOUND-SRATE* 2))
  369.        (format t "Warning: osc frequency (~A hz) will alias at current sample rate (~A hz).\n"
  370.            hz *SOUND-SRATE*)))
  371.      (set-logical-stop
  372.      (scale-db (get-loud)
  373.            (snd-osc 
  374.         (car sound)        ; samples for table
  375.         (cadr sound)        ; step represented by table
  376.         *SOUND-SRATE*        ; output sample rate
  377.         hz            ;  output hz
  378.         *rslt*            ; starting time
  379.         d            ; duration
  380.         phase))                 ; phase
  381.      duration)))
  382.  
  383.  
  384. ;; PARTIAL -- sine osc with built-in envelope scaling
  385. ;;
  386. (defun partial (steps env)
  387.   (let ((hz (step-to-hz (+ steps (get-transpose)))))
  388.     (cond ((> hz (/ *SOUND-SRATE* 2))
  389.        (format t "Warning: partial frequency (~A hz) will alias at current sample rate (~A hz).\n"
  390.            hz *SOUND-SRATE*)))
  391.     (snd-partial *sound-srate*
  392.          hz
  393.          env)))
  394.  
  395.  
  396. ;; SAMPLER -- simple attack + sustain sampler
  397. ;;
  398. (defun sampler (pitch modulation 
  399.         &optional (sample *table*) (npoints 2))
  400.   (let ((samp (car sample))
  401.     (samp-pitch (cadr sample))
  402.     (samp-loop-start (caddr sample))
  403.     (hz (step-to-hz (+ pitch (get-transpose)))))
  404.     ; make a waveform table look like a sample with no attack:
  405.     (cond ((not (numberp samp-loop-start))
  406.        (setf samp-loop-start 0.0)))
  407.     (cond ((> hz (/ *SOUND-SRATE* 2))
  408.        (format t "Warning: sampler nominal frequency (~A hz) will alias at current sample rate (~A hz).\n"
  409.            hz *SOUND-SRATE*)))
  410.     (scale-db (get-loud)
  411.        (snd-sampler 
  412.     samp        ; samples for table
  413.     samp-pitch        ; step represented by table
  414.     samp-loop-start         ; time to start loop
  415.     *SOUND-SRATE*        ; output sample rate
  416.     hz            ;  output hz
  417.     (local-to-global 0)    ; starting time
  418.     modulation        ; modulation
  419.     npoints))))        ; number of interpolation points
  420.  
  421.  
  422. ;; SINE -- simple sine oscillator
  423. ;;
  424. (defun sine (steps &optional (duration 1.0))
  425.   (let ((hz (step-to-hz (+ steps (get-transpose))))
  426.     (d (get-duration duration)))
  427.     (cond ((> hz (/ *SOUND-SRATE* 2))
  428.        (format t "Warning: sine frequency (~A hz) will alias at current sample rate (~A hz).\n"
  429.            hz *SOUND-SRATE*)))
  430.     (snd-sine *rslt* hz *sound-srate* d)))
  431.  
  432.  
  433. ;; PLUCK
  434. ;;
  435. ;; (ARGUMENTS ("double" "sr") ("double" "hz") ("time_type" "t0") 
  436. ;;            ("time_type" "d") ("double" "final_amp"))
  437. ;;
  438. (defun pluck (steps &optional (duration 1.0) (final-amp 0.001))
  439.   (let ((hz (step-to-hz (+ steps (get-transpose))))
  440.         (d (get-duration duration)))
  441.     (cond ((> hz (/ *SOUND-SRATE* 2))
  442.        (format t "Warning: pluck frequency (~A hz) will alias at current sample rate (~A hz).\n"
  443.            hz *SOUND-SRATE*)))
  444.     (snd-pluck *SOUND-SRATE* hz *rslt* d final-amp)))
  445.  
  446.  
  447.  
  448.  
  449. ;; abs-env -- restore the standard environment
  450. ;;
  451. (defmacro abs-env (s)
  452.   `(progv '(*WARP* *LOUD* *TRANSPOSE* *SUSTAIN* 
  453.         *START* *STOP* *CONTROL-SRATE* *SOUND-SRATE*)
  454.       (list '(0.0 1.0 NIL) 0.0 0.0 1.0
  455.         -1e+9 1e+9 *DEFAULT-CONTROL-SRATE* *DEFAULT-SOUND-SRATE*)
  456.       ,s))
  457.  
  458.  
  459. ; nyq:add2 - add two arguments
  460. (defun nyq:add2 (s1 s2)
  461.     (cond ((and (arrayp s1) (not (arrayp s2)))
  462.        (setf s2 (vector s2)))
  463.       ((and (arrayp s2) (not (arrayp s1)))
  464.        (setf s1 (vector s1))))
  465.     (cond ((arrayp s1)
  466.        (sum-of-arrays s1 s2))
  467.       (t
  468.        (nyq:add-2-sounds s1 s2))))
  469.  
  470.  
  471. ; (NYQ:ADD-2-SOUNDS S1 S2) - add two sound (or number) arguments
  472. (defun nyq:add-2-sounds (s1 s2)
  473.   (cond ((numberp s1)
  474.      (cond ((numberp s2)
  475.         (+ s1 s2))
  476.            (t
  477.         (snd-offset s2 s1))))
  478.     ((numberp s2)
  479.      (snd-offset s1 s2))
  480.     (t
  481.      (let ((s1sr (snd-srate s1))
  482.            (s2sr (snd-srate s2)))
  483. ;    (display "nyq:add-2-sounds" s1sr s2sr)
  484.        (cond ((> s1sr s2sr)
  485.           (snd-add s1 (snd-up s1sr s2)))
  486.          ((< s1sr s2sr)
  487.           (snd-add (snd-up s2sr s1) s2))
  488.          (t
  489.           (snd-add s1 s2)))))))
  490.  
  491.  
  492.  
  493.  
  494. (defmacro at (x s)
  495.  `(progv '(*WARP*) (list (list (+ (warp-time *WARP*) 
  496.                   (* (warp-stretch *WARP*) ,x))
  497.                    (warp-stretch *WARP*)
  498.                    (warp-function *WARP*)))
  499.       ,s))
  500.  
  501.  
  502. ;; (AT-ABS t behavior) evaluate behavior at global time t
  503. ;;
  504. ;; *WARP* is the triple (d s f) denoting the function f(st+d),
  505. ;; a mapping from local to global time.
  506. ;; We want (d' s f) such that f(s*0 + d') = t
  507. ;; (Note that we keep the same s and f, and only change the offset.
  508. ;; To eliminate the warp and stretch use "(abs-env (at t behavior))")
  509. ;; Applying the inverse of f, d' = f-1(t), or (sref (snd-inverse f ...) t)
  510. ;; Rather than invert the entire function just to evaluate at one point,
  511. ;; we use SREF-INVERSE to find d'.
  512. ;;
  513. (defmacro at-abs (x s)
  514.  `(progv '(*WARP*)
  515.      (if (warp-function *WARP*)
  516.                (list (list (sref-inverse (warp-function *WARP*) ,x)
  517.                    (warp-stretch *WARP*)
  518.                    (warp-function *WARP*)))
  519.                (list (list ,x (warp-stretch *WARP*) NIL)))
  520.      ,s))
  521.  
  522. ;; (CLIP S1 VALUE) - clip maximum amplitude to value
  523. ;
  524. (defun clip (x v)
  525.   (cond ((numberp x)
  526.      (max (min x v) (- v)))
  527.     ((arrayp x)
  528.      (let* ((len (length x))
  529.         (result (make-array len)))
  530.         (dotimes (i len)
  531.         (setf (aref result i) 
  532.               (snd-clip (aref x i) v)))
  533.         result))
  534.     (t
  535.      (snd-clip x v))))
  536.  
  537. ;; (NYQ:COERCE-TO S1 S2) - expand sound s1 to type of s2
  538. (defun nyq:coerce-to (s1 s2)
  539.   (cond ((soundp s1)
  540.      (cond ((arrayp s2)
  541.         (nyq:sound-to-array s1 (length s2)))
  542.            (t s1)))
  543.     (t s1)))
  544.  
  545.  
  546. (defmacro continuous-control-warp (beh)
  547.   `(snd-compose (warp-abs nil ,beh)
  548.         (snd-inverse (get-warp)
  549.          (local-to-global 0) *control-srate*)))
  550.  
  551. (defmacro continuous-sound-warp (beh)
  552.   `(snd-compose (warp-abs nil ,beh)
  553.         (snd-inverse (get-warp)
  554.          (local-to-global 0) *sound-srate*)))
  555.  
  556.  
  557. (defmacro control-srate-abs (r s)
  558.   `(progv '(*CONTROL-SRATE*) (list ,r)
  559.       ,s))
  560.  
  561. ; db = 20log(ratio)
  562. ; db = 20 ln(ratio)/ln(10)
  563. ; db/20 = ln(ratio)/ln(10)
  564. ; db ln(10)/20 = ln(ratio)
  565. ; e^(db ln(10)/20) = ratio
  566. ;
  567. (setf ln10over20 (/ (log 10.0) 20))
  568.  
  569. (defun db-to-linear (x) 
  570.   (cond ((numberp x)
  571.      (exp (* ln10over20 x)))
  572.     ((arrayp x)
  573.      (let* ((len (length x))
  574.         (result (make-array len)))
  575.         (dotimes (i len)
  576.         (setf (aref result i) 
  577.               (snd-exp (snd-scale ln10over20 (aref snd i)))))
  578.         result))
  579.     (t
  580.      (snd-exp (snd-scale ln10over20 x)))))
  581.  
  582.  
  583. (defun linear-to-db (x) 
  584.   (cond ((numberp x)
  585.      (/ (log (float x)) ln10over20))
  586.     ((arrayp x)
  587.      (let* ((len (length x))
  588.         (result (make-array len)))
  589.         (dotimes (i len)
  590.         (setf (aref result i) 
  591.               (snd-scale (/ 1.0 ln10over20) (snd-log (aref snd i)))))
  592.         result))
  593.     (t
  594.      (snd-scale (/ 1.0 ln10over20) (snd-log x)))))
  595.  
  596. ; sref - access a sound at a given time point
  597. ;    note that the time is transformed to global
  598. (defun sref (sound point)
  599.   (snd-sref sound (local-to-global point)))
  600.  
  601.  
  602. ; extract - start is stretched and shifted as is stop
  603. ;  result is shifted to start at local time zero
  604. (defun extract (start stop sound)
  605.   (snd-xform sound (snd-srate sound) (local-to-global 0) 
  606.          (local-to-global start) (local-to-global stop) 1.0))
  607.  
  608. (defun extract-abs (start stop sound)
  609.   (snd-xform sound (snd-srate sound) 0 start stop 1.0))
  610.      
  611.  
  612. ;(defmacro extract (start stop sound)
  613. ;  `(let ($newsound)
  614. ;     (progv '(*START* *STOP*)
  615. ;            (list (local-to-global ,start)
  616. ;          (local-to-global ,stop))
  617. ;            (setf $newsound ,sound)
  618. ;            (setf $newsound 
  619. ;                  (loud-abs 0 (cue (set-logical-stop-abs $newsound *STOP*)))))
  620. ;     $newsound))
  621.  
  622.  
  623. ;(defmacro extract-abs (start stop sound)
  624. ;  `(let ($newsound $newstart)
  625. ;     (progv '(*START* *STOP*)
  626. ;            (list ,start ,stop)
  627. ;        (setf $newstart *START*)
  628. ;            (setf $newsound ,sound)            
  629. ;            (setf $newsound (set-logical-stop-abs $newsound *STOP*)))
  630. ;     (snd-xform $newsound (snd-srate $newsound) ,start ,stop 1.0)))
  631.  
  632.  
  633. (defun local-to-global (local-time)
  634.   (let ((d (warp-time *WARP*))
  635.     (s (warp-stretch *WARP*))
  636.     (w (warp-function *WARP*))
  637.     global-time)
  638.     (setf global-time (+ (* s local-time) d))
  639.     (if w (snd-sref w global-time) global-time)))
  640.  
  641.  
  642. (defmacro loud (x s)
  643.  `(progv '(*LOUD*) (list (sum *LOUD* ,x))
  644.      ,s))
  645.  
  646.  
  647. (defmacro loud-abs (x s)
  648.  `(progv '(*LOUD*) (list ,x)
  649.      ,s))
  650.  
  651. (defun must-be-sound (x)
  652.  (cond ((soundp x) x)
  653.        (t
  654.     (error "SOUND type expected" x))))
  655.  
  656. ;; SCALE-DB -- same as scale, but argument is in db
  657. ;;
  658. (defun scale-db (factor sound)
  659.   (scale (db-to-linear factor) sound))
  660.  
  661. (defun set-control-srate (rate)
  662.   (setf *default-control-srate* (float rate))
  663.   (nyq:environment-init))
  664.  
  665. (defun set-sound-srate (rate) 
  666.   (setf *default-sound-srate* (float rate))
  667.   (nyq:environment-init))
  668.  
  669.  
  670. ; s-plot -- compute and write n data points for plotting
  671. (defun s-plot (snd &optional (n 1000))
  672.   (prog ((points (snd-samples snd (1+ n)))
  673.      (filename (soundfilename *default-plot-file*))
  674.      outf
  675.      (period (/ 1.0 (snd-srate snd)))
  676.      len 
  677.      (maximum 1.0))
  678.     (setf outf (open filename :direction :output))
  679.     (cond ((null outf)
  680.        (format t "s-plot: could not open ~A!~%" filename)
  681.        (return nil)))
  682.     (format t "s-plot: writing ~A ... ~%" filename)
  683.     (setf len (length points))
  684.     (cond ((> len n)
  685.        (setf len n)
  686.        (format t "WARNING: SOUND TRUNCATED TO ~A POINTS~%" len)))
  687.     (dotimes (i len)
  688.       (cond ((< (abs maximum) (abs (aref points i)))
  689.          (setf maximum (aref points i))))
  690.       (format outf "~A ~A~%" (* i period) (aref points i)))
  691.     (close outf)
  692.     (cond ((> (abs maximum) 1.0)
  693.        (format t "WARNING: MAXIMUM AMPLITUDE IS ~A~%" maximum)))
  694.     (format t "~A points from ~A to ~A~%"
  695.      len (snd-t0 snd) (+ (snd-t0 snd) (* len period)))))
  696.  
  697. ; run something like this to plot the points:
  698. ; graph < points.dat | plot -Ttek
  699.  
  700.  
  701. (defmacro sound-srate-abs (r s)
  702.   `(progv '(*SOUND-SRATE*) (list ,r)
  703.       ,s))
  704.  
  705.  
  706. (defmacro stretch (x s)
  707.  `(progv '(*WARP*) (list (list (warp-time *WARP*) 
  708.                    (* (warp-stretch *WARP*) ,x)
  709.                    (warp-function *WARP*)))
  710.      (if (minusp (warp-stretch *WARP*))
  711.          (break "Negative stretch factor is not allowed"))
  712.              ,s))
  713.  
  714.          
  715. (defmacro stretch-abs (x s)
  716.  `(progv '(*WARP*) (list (list (local-to-global 0)
  717.                    ,x
  718.                    nil))
  719.      (if (minusp (warp-stretch *WARP*))
  720.          (break "Negative stretch factor is not allowed"))
  721.              ,s))
  722.  
  723.  
  724. (defmacro sustain (x s)
  725.  `(progv '(*SUSTAIN*) (list (prod *SUSTAIN* ,x))
  726.       ,s))
  727.  
  728.  
  729. (defmacro sustain-abs (x s)
  730.  `(progv '(*SUSTAIN*) (list ,x)
  731.       ,s))
  732.  
  733.  
  734. ;; (WARP-FUNCTION *WARP*) - extracts function field of warp triple
  735. ;;
  736. (setfn warp-function caddr)
  737.  
  738.  
  739. ;; (WARP-STRETCH *WARP*) - extracts stretch field of warp triple
  740. ;;
  741. (setfn warp-stretch cadr)
  742.  
  743.  
  744. ;; (WARP-TIME *WARP*) - extracts time field of warp triple
  745. ;;
  746. (setfn warp-time car)
  747.  
  748.  
  749. (defmacro transpose (x s)
  750.  `(progv '(*TRANSPOSE*) (list (sum *TRANSPOSE* ,x))
  751.       ,s))
  752.  
  753.  
  754. (defmacro transpose-abs (x s)
  755.  `(progv '(*TRANSPOSE*) (list ,x)
  756.       ,s))
  757.  
  758.  
  759. ;; CONTROL-WARP -- apply a warp function to a control function
  760. ;; 
  761. (defun control-warp (warp-fn control &optional wrate)
  762.   (cond (wrate
  763.      (snd-resamplev control *control-srate*
  764.             (snd-inverse warp-fn (local-to-global 0) wrate)))
  765.     (t
  766.      (snd-compose control
  767.               (snd-inverse warp-fn (local-to-global 0) *control-srate*)))))
  768.  
  769.  
  770. ;; (cue sound)
  771. ;;    Cues the given sound; that is, it applies the current *WARP*, *LOUD*,
  772. ;; *START*, and *STOP* values to the argument.  The logical start time is at
  773. ;; local time 0.
  774. (defun cue (sound)
  775.   (cond ((arrayp sound)
  776.      (let* ((len (length sound))
  777.         (result (make-array len)))
  778.         (dotimes (i len)
  779.         (setf (aref result i)
  780.               (cue-sound (aref sound i))))
  781.         result))
  782.     (t
  783.      (cue-sound sound))))
  784.  
  785. (defun cue-sound (sound)
  786.   (snd-xform sound
  787.          (snd-srate sound)
  788.          (local-to-global 0) *START* *STOP* (db-to-linear (get-loud))))
  789.  
  790. ;; (sound sound)
  791. ;;    Same as (cue sound), except also warps the sound.
  792. ;; Note that the *WARP* can change the pitch of the
  793. ;; sound as a result of resampling.
  794. ;; Here's the derivation for the warping code:
  795. ;; *WARP* is a triple: (d s f) which denotes that the warp from local to
  796. ;; global time is: f(st+d)
  797. ;; We need to compose sound with the inverse of this to get a function
  798. ;; of global time
  799. ;; Let f-1 be the inverse of f.  Then the inverse of f(st+d) is 
  800. ;; (f-1(t) - d)/s
  801. ;; The composition gives us: (snd-compose sound (f-1(t) - d)/s)
  802. ;; Eliminate the 1/s term by changing the sample rate of sound:
  803. ;;  = (snd-compose (snd-scale-srate sound s) (f-1(t) - d))
  804. ;; Eliminate the -d term by shifting f before taking the inverse:
  805. ;;  = (snd-compose (scale-srate sound s) ((inverse f) - d))
  806. ;;  = (snd-compose (scale-srate sound s) (inverse f(t + d)))
  807. ;;  = (snd-compose (scale-srate sound s) (inverse (shift f -d)))
  808. ;; snd-inverse takes a time and sample rate.  For time, use zero.
  809. ;; The sample rate of inverse determines the final sample rate of
  810. ;; this function, so use *SOUND-SRATE*:
  811. ;;  = (snd-compose (scale-srate sound s) (snd-inverse (shift-time f (- d))
  812. ;;                                              0 *SOUND-SRATE*))
  813. ;;
  814. (defun sound (sound)
  815.    (cond ((null (warp-function *WARP*))
  816.       (snd-xform sound (/ (snd-srate sound) (warp-stretch *WARP*))
  817.              (local-to-global 0)
  818.              *START* *STOP* (db-to-linear (get-loud))))
  819.      (t
  820.       (snd-compose (scale-srate sound (warp-stretch *WARP*))
  821.                (snd-inverse (shift-time (warp-function *WARP*)
  822.                         (- (warp-time *WARP*)))
  823.                     0 *SOUND-SRATE*)))))
  824.  
  825.  
  826. ;; (SCALE-SRATE SOUND SCALE)
  827. ;; multiplies the sample rate by scale
  828. (defun scale-srate (sound scale)
  829.   (let ((new-srate (* scale (snd-srate sound))))
  830.     (snd-xform sound new-srate (snd-time sound) 
  831.            MIN-START-TIME MAX-STOP-TIME 1.0)))
  832.  
  833.  
  834. ;; (SHIFT-TIME SOUND SHIFT)
  835. ;; shift the time of a function by SHIFT, i.e. if SOUND is f(t),
  836. ;; then (shift-time SOUND SHIFT) is f(t - SHIFT).  Note that if
  837. ;; you look at plots, the shifted sound will move *right* when SHIFT
  838. ;; is positive.  
  839. (defun shift-time (sound shift)
  840.   (snd-xform sound (snd-srate sound) (+ (snd-t0 sound) shift)
  841.          MIN-START-TIME MAX-STOP-TIME 1.0))
  842.  
  843.  
  844. ;; (NYQ:SOUND-TO-ARRAY SOUND N) - duplicate SOUND to N channels
  845. ;;
  846. (defun nyq:sound-to-array (sound n)
  847.   (let ((result (make-array n)))
  848.     (dotimes (i n)
  849.       (setf (aref result i) sound))
  850.     result))
  851.  
  852.  
  853. ;; (control sound)
  854. ;;    Same as (sound sound), except this is used for control signals.  
  855. ;;    This code is identical to sound.
  856. (setfn control sound)
  857.  
  858.  
  859. ;; (env t1 t2 t4 l1 l2 l3 &optional duration)
  860. ;; Creates a 4-phase envelope.
  861. ;;    tN is the duration of phase N, and lN is the final level of
  862. ;;    phase N.  t3 is implied by the duration, and l4 is 0.0.
  863. ;;    If dur is not supplied, then 1.0 is assumed.  The envelope
  864. ;;    duration is the product of dur, *STRETCH*, and *SUSTAIN*.  If 
  865. ;;    t1 + t2 + 2ms + t4 > duration, then a two-phase envelope is
  866. ;;    substituted that has an attack/release time ratio = t1/t4.
  867. ;;    The sample rate of the returned sound is *CONTROL-SRATE*.
  868. ;;
  869. ;; Time transformation: the envelope is not warped; the start time and
  870. ;; stop times are warped to global time.  Then the value of *SUSTAIN* at
  871. ;; the begining of the envelope is used to determing absolute duration.
  872. ;; Since PWL is ultimately called to create the envelope, we must use
  873. ;; ABS-ENV to prevent any further transforms inside PWL.  We use
  874. ;; (AT global-start ...) inside ABS-ENV so that the final result has 
  875. ;; the proper starting time.
  876. ;;
  877. (defun env (t1 t2 t4 l1 l2 l3 &optional (duration 1.0))
  878.   (let (actual-dur min-dur ratio t3
  879.     (actual-dur (get-duration duration)))
  880.     (setf min-dur (+ t1 t2 t4 0.002))
  881.     (cond ((< actual-dur min-dur)
  882.        (setf ratio (/ t1 (+ t1 t4)))
  883.        (setf t1 (* ratio actual-dur))
  884.        (setf t2 (- actual-dur t1))
  885.        (setf t3 0.0)
  886.        (setf t4 0.0)
  887.        (setf l2 0.0)
  888.        (setf l3 0.0))
  889.       (t
  890.        (setf t3 (- actual-dur t1 t2 t4))))
  891.     (set-logical-stop
  892.      (abs-env (at *rslt*
  893.           (pwl t1 l1 (+ t1 t2) l2 (- actual-dur t4) l3 actual-dur)))
  894.      duration)))
  895.  
  896.  
  897. (defun gate (sound lookahead risetime falltime floor threshold)
  898.     (cond ((< lookahead risetime)
  899.            (break "lookahead must be greater than risetime in GATE function"))
  900.           ((or (< risetime 0) (< falltime 0) (< floor 0))
  901.            (break "risetime, falltime, and floor must all be positive in GATE function"))
  902.           (t
  903.            (let ((s
  904.               (snd-gate (seq (cue sound) (abs-env (s-rest lookahead)))
  905.                     lookahead risetime falltime floor threshold)))
  906.              (snd-xform s (snd-srate s) (snd-t0 sound) 
  907.             (+ (snd-t0 sound) lookahead) MAX-STOP-TIME 1.0)))))
  908.  
  909.  
  910. ;; (osc-note step &optional duration env sust volume sound)
  911. ;;   Creates a note using table-lookup osc, but with an envelope.
  912. ;; The ENV parameter may be a parameter list for the env function,
  913. ;; or it may be a sound.
  914. ;;
  915. (defun osc-note (pitch &optional (duration 1.0) 
  916.                (env-spec '(0.02 0.1 0.3 1.0 .8 .7))
  917.                (volume 0.0)
  918.                (table *TABLE*))
  919.   (set-logical-stop
  920.    (mult (loud volume (osc pitch duration table))
  921.      (if (listp env-spec)
  922.        (apply 'env env-spec)
  923.        env-spec))
  924.    duration))
  925.  
  926.  
  927. ;; force-srate -- resample snd if necessary to get sample rate
  928. ;
  929. (defun force-srate (sr snd)
  930.   (cond ((not (numberp sr))
  931.      (error "force-srate: SR should be a number")))
  932.   (cond ((arrayp snd)
  933.      (let* ((len (length snd))
  934.         (result (make-array len)))
  935.        (dotimes (i len)
  936.             (setf (aref result i) 
  937.               (force-srate sr (aref snd i))))
  938.        result))
  939.     (t
  940.      (let ((snd-sr (snd-srate snd)))
  941.        (cond ((> sr snd-sr) (snd-up sr snd))
  942.          ((< sr snd-sr) (snd-down sr snd))
  943.          (t snd))))))
  944.  
  945.  
  946. (defun force-srates (srs snd)
  947.   (cond ((and (numberp srs) (soundp snd))
  948.      (force-srate srs snd))
  949.     ((and (arrayp srs) (arrayp snd))
  950.      (let* ((len (length snd))
  951.         (result (make-array len)))
  952.        (dotimes (i len)
  953.             (setf (aref result i) 
  954.               (force-srate (aref srs i) (aref snd i))))
  955.        result))
  956.     (t (error "arguments not compatible"))))
  957.  
  958.  
  959. ;; (breakpoints-convert (t1 x1 t2 x2 ... tn) t0)
  960. ;;   converts times to sample numbers and scales amplitudes
  961. ;;   t0 is the global (after warping) start time
  962. ;;
  963. ;; NOTE: there were some stack overflow problems with the original
  964. ;; recursive version (in comments now), so it was rewritten as an
  965. ;; iteration.
  966. ;;
  967. (defun breakpoints-convert (list t0)
  968.   (prog (sample-count result sust (last-count 0))
  969.     (setf sust (get-sustain))
  970.  loop
  971.     (setf sample-count 
  972.       (truncate (+ 0.5 (* (- (local-to-global (* (car list) sust)) t0)
  973.                  *control-srate*))))
  974.     ; now we have a new sample count to put into result list
  975.     ; make sure result is non-decreasing
  976.     (cond ((< sample-count last-count)
  977.        (setf sample-count last-count)))
  978.     (setf last-count sample-count)
  979.     (push sample-count result)
  980.     (cond ((cdr list)
  981.        (setf list (cdr list))
  982.        (push (float (car list)) result)))
  983.     (setf list (cdr list))
  984.     (cond (list
  985.        (go loop)))
  986.     (return (reverse result))))
  987.  
  988.       
  989.  
  990. ;; (pwl t1 l1 t2 l2 ... tn)
  991. ;;   Creates a piece-wise linear envelope from breakpoint data.
  992. ;;
  993. (defun pwl (&rest breakpoints) (pwl-list breakpoints))
  994.  
  995. (defun pwlr (&rest breakpoints) (pwlr-list breakpoints))
  996.  
  997. ;; (breakpoints-relative list)
  998. ;;  converts list, which has the form (value dur value dur value ...)
  999. ;;  into the form (value time value time value ...)
  1000. ;;  the list may have an even or odd length
  1001. ;;
  1002. (defun breakpoints-relative (breakpoints)
  1003.   (prog (result (sum 0.0))
  1004.  loop
  1005.      (cond (breakpoints
  1006.         (push (car breakpoints) result)
  1007.         (setf breakpoints (cdr breakpoints))
  1008.         (cond (breakpoints
  1009.            (setf sum (+ sum (car breakpoints)))
  1010.            (push sum result)
  1011.            (setf breakpoints (cdr breakpoints))
  1012.            (go loop)))))
  1013.      (return (reverse result))))
  1014.  
  1015.  
  1016. (defun breakpoints-relative (breakpoints)
  1017.   (prog (result (sum 0.0))
  1018.  loop
  1019.     (setf sum (+ sum (car breakpoints)))
  1020.     (push sum result)
  1021.     (cond ((cdr breakpoints)
  1022.        (setf breakpoints (cdr breakpoints))
  1023.        (push (car breakpoints) result)))
  1024.     (setf breakpoints (cdr breakpoints))
  1025.     (cond (breakpoints
  1026.        (go loop)))
  1027.     (return (reverse result))))
  1028.  
  1029.  
  1030. (defun pwlr-list (breakpoints)
  1031.   (pwl-list (breakpoints-relative breakpoints)))
  1032.  
  1033. (defun pwl-list (breakpoints)
  1034.   (let ((t0 (local-to-global 0)))
  1035.     (snd-pwl t0 *control-srate* (breakpoints-convert breakpoints t0))))
  1036.  
  1037. ;; (pwlv l1 t1 l2 t2 ... ln)
  1038. ;; Creates a piece-wise linear envelope from breakpoint data;
  1039. ;; the function initial and final values are explicit
  1040. ;;
  1041. (defun pwlv (&rest breakpoints)
  1042.   ;use pwl, modify breakpoints with initial and final changes
  1043.   ;need to put initial time of 0, and final time of 0
  1044.   (pwlv-list breakpoints))
  1045.  
  1046. (defun pwlv-list (breakpoints)
  1047.     (pwl-list (cons 0.0 (append breakpoints '(0.0)))))
  1048.  
  1049. (defun pwlvr (&rest breakpoints) (pwlvr-list breakpoints))
  1050.  
  1051. (defun pwlvr-list (breakpoints)
  1052.   (pwlr-list (cons 0.0 (append breakpoints '(0.0)))))
  1053.  
  1054. (defun pwe (&rest breakpoints)
  1055.   (pwe-list breakpoints))
  1056.  
  1057. (defun pwe-list (breakpoints)
  1058.   (pwev-list (cons 1.0 (append breakpoints '(1.0)))))
  1059.  
  1060. (defun pwer (&rest breakpoints) (pwer-list breakpoints))
  1061.  
  1062. (defun pwer-list (breakpoints)
  1063.   (pwe-list (breakpoints-relative breakpoints)))
  1064.  
  1065. (defun pwev (&rest breakpoints)
  1066.   (pwev-list breakpoints))
  1067.  
  1068. (defun pwev-list (breakpoints)
  1069.   (let ((lis (breakpoints-log breakpoints)))
  1070.     (s-exp (pwl-list lis))))
  1071.  
  1072. (defun pwevr (&rest breakpoints) (pwevr-list breakpoints))
  1073.  
  1074. (defun pwevr-list (breakpoints)
  1075.   (pwev-list (cdr (breakpoints-relative (cons 0.0 breakpoints)))))
  1076.  
  1077.  
  1078. (defun breakpoints-log (breakpoints)
  1079.   (prog ((result '(0.0)) val tim)
  1080. loop
  1081.     (cond (breakpoints
  1082.        (setf val (float (car breakpoints)))
  1083.        (setf breakpoints (cdr breakpoints))
  1084.        (cond (breakpoints
  1085.           (setf tim (car breakpoints))
  1086.           (setf breakpoints (cdr breakpoints))))
  1087.        (setf result (cons tim (cons (log val) result)))
  1088.        (cond ((null breakpoints)
  1089.           (return (reverse result))))
  1090.        (go loop))
  1091.       (t
  1092.        (error "Expected odd number of elements in breakpoint list")))))
  1093.  
  1094.  
  1095. ;; SOUND-WARP -- apply warp function to a sound
  1096. ;; 
  1097. (defun sound-warp (warp-fn signal &optional wrate)
  1098.   (cond (wrate
  1099.      (snd-resamplev signal *sound-srate*
  1100.             (snd-inverse warp-fn (local-to-global 0) wrate)))
  1101.     (t
  1102.      (snd-compose signal 
  1103.               (snd-inverse warp-fn (local-to-global 0) *sound-srate*)))))
  1104.  
  1105. (defun snd-extent (sound maxsamples) 
  1106.     (list (snd-t0 sound)
  1107.       (+ (snd-t0 sound) (/ (snd-length sound maxsamples)
  1108.                    (snd-srate sound)))))
  1109.  
  1110. (setfn snd-flatten snd-length)
  1111.  
  1112. ;; (maketable sound)
  1113. ;;   Creates a table for osc, lfo, etc. by assuming that the samples
  1114. ;;   in sound represent one period.  The sound must start at time 0.
  1115.  
  1116. (defun maketable (sound)
  1117.   (list sound
  1118.     (hz-to-step 
  1119.      (/ 1.0
  1120.         (cadr (snd-extent sound 1000000))))
  1121.     T))
  1122.  
  1123.  
  1124. ;(defmacro endTime (sound)
  1125. ;   `(get-logical-stop ,sound))
  1126.  
  1127.  
  1128. ;(defmacro beginTime (sound)
  1129. ;   `(car (snd-extent ,sound)))
  1130.  
  1131.  
  1132. ; simple stereo pan: as where goes from 0 to 1, sound
  1133. ; is linearly panned from left to right
  1134. ;
  1135. (defun pan (sound where)
  1136.   (vector (mult sound (sum 1 (mult -1 where)))
  1137.       (mult sound where)))
  1138.  
  1139.  
  1140. (defun prod (&rest snds)
  1141.   (cond ((null snds)
  1142.      (snd-zero (local-to-global 0) *sound-srate*))
  1143.     ((null (cdr snds))
  1144.      (car snds))
  1145.     ((null (cddr snds))
  1146.      (nyq:prod2 (car snds) (cadr snds)))
  1147.     (t
  1148.      (nyq:prod2 (car snds) (apply #'prod (cdr snds))))))
  1149.  
  1150. (setfn mult prod)
  1151.  
  1152.  
  1153. ;; (NYQ:PROD-OF-ARRAYS S1 S2) - form pairwise products
  1154. ;
  1155. (defun nyq:prod-of-arrays (s1 s2)
  1156.   (let* ((n (length s1))
  1157.      (p (make-array n)))
  1158.     (cond ((/= n (length s2))
  1159.        (error "unequal number of channels in prod")))
  1160.     (dotimes (i n)
  1161.       (setf (aref p i) (nyq:prod2 (aref s1 i) (aref s2 i))))
  1162.     p))
  1163.  
  1164.  
  1165. ; nyq:prod2 - multiply two arguments
  1166. (defun nyq:prod2 (s1 s2)
  1167.   (setf s1 (nyq:coerce-to s1 s2))
  1168.   (setf s2 (nyq:coerce-to s2 s1))
  1169.   (cond ((arrayp s1)
  1170.      (nyq:prod-of-arrays s1 s2))
  1171.     (t
  1172.      (nyq:prod-2-sounds s1 s2))))
  1173.  
  1174.  
  1175. ; (PROD-2-SOUNDS S1 S2) - multiply two sound arguments
  1176. (defun nyq:prod-2-sounds (s1 s2)
  1177.   (cond ((numberp s1)
  1178.      (cond ((numberp s2)
  1179.         (* s1 s2))
  1180.            (t
  1181.         (scale s1 s2))))
  1182.     ((numberp s2)
  1183.      (scale s2 s1))
  1184.     (t
  1185.      (let ((s1sr (snd-srate s1))
  1186.            (s2sr (snd-srate s2)))
  1187. ;    (display "nyq:prod-2-sounds" s1sr s2sr)
  1188.         (cond ((> s1sr s2sr)
  1189.            (snd-prod s1 (snd-up s1sr s2)))
  1190.           ((< s1sr s2sr)
  1191.            (snd-prod (snd-up s2sr s1) s2))
  1192.           (t
  1193.            (snd-prod s1 s2)))))))
  1194.  
  1195.  
  1196. ;; RAMP -- linear ramp from 0 to x
  1197. ;;
  1198. (defun ramp (&optional (x 1))
  1199.   (let* ((duration (get-duration x)))
  1200.     (warp-abs nil 
  1201.     (at *rslt*
  1202.         (sustain-abs 1
  1203.         (pwl duration 1 (+ duration (/ *control-srate*))))))))
  1204.  
  1205.  
  1206. (defun resample (snd rate)
  1207.   (cond ((arrayp snd)
  1208.      (let* ((len (length snd))
  1209.         (result (make-array len)))
  1210.         (dotimes (i len)
  1211.         (setf (aref result i)
  1212.               (snd-resample (aref snd i) rate)))
  1213.         result))
  1214.     (t
  1215.      (snd-resample snd rate))))
  1216.  
  1217.  
  1218. (defun scale (amt snd)
  1219.   (cond ((arrayp snd)
  1220.      (let* ((len (length snd))
  1221.         (result (make-array len)))
  1222.         (dotimes (i len)
  1223.         (setf (aref result i) (snd-scale amt (aref snd i))))
  1224.         result))
  1225.     (t
  1226.      (snd-scale amt snd))))
  1227.  
  1228.  
  1229. (setfn s-print-tree snd-print-tree)
  1230.  
  1231. ;; (PEAK sound-expression number-of-samples) - find peak amplitude
  1232. ;
  1233. ; NOTE: this used to be called s-max
  1234. ;
  1235. (defmacro peak (expression maxlen)
  1236.    `(snd-max ',expression ,maxlen))
  1237.  
  1238. ;; (S-MAX S1 S2) - return maximum of S1, S2
  1239. ;
  1240. (defun s-max (s1 s2)
  1241.   (setf s1 (nyq:coerce-to s1 s2))
  1242.   (setf s2 (nyq:coerce-to s2 s1))
  1243.   (cond ((arrayp s1)
  1244.      (nyq:max-of-arrays s1 s2))
  1245.     (t
  1246.      (nyq:max-2-sounds s1 s2))))
  1247.  
  1248. (defun nyq:max-of-arrays (s1 s2)
  1249.   (let* ((n (length s1))
  1250.      (p (make-array n)))
  1251.     (cond ((/= n (length s2))
  1252.        (error "unequal number of channels in max")))
  1253.     (dotimes (i n)
  1254.       (setf (aref p i) (s-max (aref s1 i) (aref s2 i))))
  1255.     p))
  1256.  
  1257. (defun nyq:max-2-sounds (s1 s2)
  1258.   (cond ((numberp s1)
  1259.          (cond ((numberp s2)
  1260.                 (max s1 s2))
  1261.                (t
  1262.                 (snd-maxv s2
  1263.                           (snd-const s1 (local-to-global 0.0)
  1264.                                      (snd-srate s2) (get-duration 1.0))))))
  1265.         ((numberp s2)
  1266.          (snd-maxv s1 (snd-const s2 (local-to-global 0.0)
  1267.                    (snd-srate s1) (get-duration 1.0))))
  1268.         (t
  1269.          (let ((s1sr (snd-srate s1))
  1270.                (s2sr (snd-srate s2)))
  1271.             (cond ((> s1sr s2sr)
  1272.                    (snd-maxv s1 (snd-up s1sr s2)))
  1273.                   ((< s1sr s2sr)
  1274.                    (snd-maxv (snd-up s2sr s1) s2))
  1275.                   (t
  1276.                    (snd-maxv s1 s2)))))))
  1277.  
  1278. (defun s-min (s1 s2)
  1279.   (setf s1 (nyq:coerce-to s1 s2))
  1280.   (setf s2 (nyq:coerce-to s2 s1))
  1281.   (cond ((arrayp s1)
  1282.          (nyq:min-of-arrays s1 s2))
  1283.         (t
  1284.          (nyq:min-2-sounds s1 s2))))
  1285.  
  1286. (defun nyq:min-of-arrays (s1 s2)
  1287.   (let* ((n (length s1))
  1288.      (p (make-array n)))
  1289.     (cond ((/= n (length s2))
  1290.        (error "unequal number of channels in max")))
  1291.     (dotimes (i n)
  1292.       (setf (aref p i) (s-min (aref s1 i) (aref s2 i))))
  1293.     p))
  1294.  
  1295. (defun nyq:min-2-sounds (s1 s2)
  1296.   (cond ((numberp s1)
  1297.      (cond ((numberp s2)
  1298.         (min s1 s2))
  1299.            (t
  1300.         (snd-minv
  1301.          (snd-const s1 (local-to-global 0.0)
  1302.                 (snd-srate s2) (get-duration 1.0))))))
  1303.     ((numberp s2)
  1304.      (snd-minv (snd-const s2 (local-to-global 0.0)
  1305.                 (snd-srate s1) (get-duration 1.0))))
  1306.     (t
  1307.      (let ((s1sr (snd-srate s1))
  1308.            (s2sr (snd-srate s2)))
  1309.         (cond ((> s1sr s2sr)
  1310.            (snd-minv s1 (snd-up s1sr s2)))
  1311.           ((< s1sr s2sr)
  1312.            (snd-minv (snd-up s2sr s1) s2))
  1313.           (t
  1314.            (snd-minv s1 s2)))))))
  1315.  
  1316. (defun snd-minv (s1 s2)
  1317.   (scale -1.0 (snd-maxv (scale -1.0 s1) (scale -1.0 s2))))
  1318.  
  1319. ; sequence macros SEQ and SEQREP are now in seq.lsp:
  1320. (load "seq" :verbose NIL)
  1321.  
  1322. ; set-logical-stop - modify the sound and return it, time is shifted and
  1323. ;             stretched
  1324. (defun set-logical-stop (snd tim)
  1325.   (let ((d (local-to-global tim)))
  1326.     (multichan-expand #'set-logical-stop-abs snd d)))
  1327.  
  1328.  
  1329. ; set-logical-stop-abs - modify the sound and return it
  1330. (defun set-logical-stop-abs (snd tim) (snd-set-logical-stop snd tim) snd)
  1331.  
  1332.  
  1333. (defmacro simrep (pair sound)
  1334.   `(let (_snds)
  1335.      (dotimes ,pair (push ,sound _snds))
  1336.      (sim-list _snds)))
  1337.  
  1338. (defun sim (&rest snds)
  1339.   (sim-list snds))
  1340.  
  1341. (setfn sum sim)
  1342.  
  1343. (defun sim-list (snds)
  1344.   (cond ((null snds)
  1345.      (snd-zero (local-to-global 0) *sound-srate*))
  1346.     ((null (cdr snds))
  1347.      (car snds))
  1348.     ((null (cddr snds))
  1349.      (nyq:add2 (car snds) (cadr snds)))
  1350.     (t
  1351.      (nyq:add2 (car snds) (sim-list (cdr snds))))))
  1352.  
  1353.  
  1354. ;(defun rest (&optional (dur 1.0))
  1355. ;  (cue (set-Logical-stop (* dur *stretch*) (s-create))))
  1356. (defun s-rest (&optional (dur 1.0))
  1357.   (let ((d (get-duration dur)))
  1358.     (snd-const 0.0 *rslt* *SOUND-SRATE* d)))
  1359.  
  1360.  
  1361. (defun tempo (warpfn)
  1362.   (slope (snd-inverse warpfn (local-to-global 0) *control-srate*)))
  1363.  
  1364.  
  1365.  
  1366. ;; (SUM-OF-ARRAYS S1 S2) - add multichannel sounds
  1367. ; result has as many channels the largest of s1, s2
  1368. ; corresponding channels are added, extras are copied
  1369. (defun sum-of-arrays (s1 s2)
  1370.   (let* ((n1 (length s1))
  1371.      (n2 (length s2))
  1372.      (n (min n1 n2))
  1373.      (m (max n1 n2))
  1374.      (result (make-array m))
  1375.      (big-s (if (> n1 n2) s1 s2)))
  1376.     
  1377.     (dotimes (i n)
  1378.       (setf (aref result i) (nyq:add-2-sounds (aref s1 i) (aref s2 i))))
  1379.     (dotimes (i (- m n))
  1380.       (setf (aref result (+ n i)) (aref big-s (+ n i))))
  1381.     result))
  1382.  
  1383.  
  1384. ;; (WARP fn behavior) - warp behavior according to fn
  1385. ;;
  1386. ;; fn is a map from behavior time to local time, and *WARP* expresses
  1387. ;; a map from local to global time.
  1388. ;; To produce a new *WARP* for the environment, we want to compose the
  1389. ;; effect of the current *WARP* with fn.  Note that fn is also a behavior.
  1390. ;; It is evaluated in the current environment first, then it is used to
  1391. ;; modify the environment seen by behavior.
  1392. ;; *WARP* is a triple: (d s f) denoting the function f(st+d).
  1393. ;; Letting g represent the new warp function fn, we want f(st+d) o g, or
  1394. ;; f(s*g(t) + d) in the form (d' s' f').
  1395. ;; Let's do this one step at a time:
  1396. ;; f(s*g(t) + d) = f(scale(s, g) + d)
  1397. ;;               = (shift f -d)(scale(s, g))
  1398. ;;               = (snd-compose (shift-time f (- d)) (scale s g))
  1399. ;;
  1400. ;; If f in NIL, it denotes the identity mapping f(t)=t, so we can
  1401. ;; simplify:
  1402. ;; f(scale(s, g) + d) = scale(s, g) + d
  1403. ;;                    = (snd-offset (scale s g) d)
  1404.  
  1405. (defmacro warp (x s)
  1406.  `(progv '(*WARP*) (list 
  1407.             (list 0.0 1.0
  1408.               (if (warp-function *WARP*)
  1409.                   (snd-compose (shift-time (warp-function *WARP*) 
  1410.                                (- (warp-time *WARP*)))
  1411.                        (scale (warp-stretch *WARP*) 
  1412.                           (must-be-sound ,x)))
  1413.                   (snd-offset (scale (warp-stretch *WARP*) 
  1414.                          (must-be-sound ,x))
  1415.                       (warp-time *WARP*)))))
  1416.      ,s))
  1417.  
  1418.  
  1419. (defmacro warp-abs (x s)
  1420.  `(progv '(*WARP*) (list (list 0.0 1.0 ,x))
  1421.      ,s))
  1422.  
  1423.  
  1424. ;; MULTICHAN-EXPAND -- construct and return array according to args
  1425. ;;
  1426. ;; arrays are used in Nyquist to represent multiple channels
  1427. ;; if any argument is an array, make sure all array arguments
  1428. ;; have the same length.  Then, construct a multichannel result
  1429. ;; by calling fn once for each channel.  The arguments passed to
  1430. ;; fn for the i'th channel are either the i'th element of an array
  1431. ;; argument, or just a copy of a non-array argument.
  1432. ;;
  1433. (defun multichan-expand (fn &rest args)
  1434.   (let (len newlen result) ; len is a flag as well as a count
  1435.     (dolist (a args)
  1436.         (cond ((arrayp a)
  1437.            (setf newlen (length a))
  1438.            (cond ((and len (/= len newlen))
  1439.               (error (format nil "In ~A, two arguments are vectors of differing length." fn))))
  1440.            (setf len newlen))))
  1441.     (cond (len
  1442.        (setf result (make-array len))
  1443.        ; for each channel, call fn with args
  1444.        (dotimes (i len)
  1445.            (setf (aref result i)
  1446.              (apply fn
  1447.             (mapcar
  1448.                 #'(lambda (a)
  1449.                 ; take i'th entry or replicate:
  1450.                 (cond ((arrayp a) (aref a i))
  1451.                       (t a)))
  1452.                 args))))
  1453.        result)
  1454.       (t
  1455.        (apply fn args)))))
  1456.  
  1457.  
  1458. ;; SELECT-IMPLEMENTATION-? -- apply an implementation according to args
  1459. ;;
  1460. ;; There is a different Nyquist primitive for each combination of 
  1461. ;; constant (NUMBERP) and time-variable (SOUNDP) arguments.  E.g.
  1462. ;; a filter with fixed parameters differs from one with varying
  1463. ;; parameters.  In most cases, the user just calls one function,
  1464. ;; and the arguments are decoded here:
  1465.  
  1466.  
  1467. ;; SELECT-IMPLEMENTATION-1-1 -- 1 sound arg, 1 selector
  1468. ;;
  1469. (defun select-implementation-1-1 (fns snd sel1 &rest others)
  1470.   (if (numberp sel1)
  1471.     (apply (aref fns 0) (cons snd (cons sel1 others)))
  1472.     (apply (aref fns 1) (cons snd (cons sel1 others)))))
  1473.  
  1474.  
  1475. ;; SELECT-IMPLEMENTATION-1-2 -- 1 sound arg, 2 selectors
  1476. ;;
  1477. ;; choose implemenation according to args 2 and 3
  1478. ;;
  1479. (defun select-implementation-1-2 (fns snd sel1 sel2 &rest others)
  1480.   (if (numberp sel2)
  1481.     (if (numberp sel1)
  1482.       (apply (aref fns 0) (cons snd (cons sel1 (cons sel2 others))))
  1483.       (apply (aref fns 1) (cons snd (cons sel1 (cons sel2 others)))))
  1484.     (if (numberp sel1)
  1485.       (apply (aref fns 2) (cons snd (cons sel1 (cons sel2 others))))
  1486.       (apply (aref fns 3) (cons snd (cons sel1 (cons sel2 others)))))))
  1487.  
  1488. ;; some waveforms
  1489.  
  1490. (setf *saw-table* (pwlvr -1 1 1))        ; eh, creepy way to get 2205 samples.
  1491. (setf *saw-table* (list *saw-table* (hz-to-step 1) T))
  1492.  
  1493. (setf *tri-table* (pwlvr -1 0.5 1 0.5 -1))
  1494. (setf *tri-table* (list *tri-table* (hz-to-step 1) T))
  1495.  
  1496. (setf *id-shape*  (pwlvr -1 2 1 .01 1))                ; identity
  1497. (setf *step-shape* (seq (const -1) (const 1 1.01)))  ; hard step at zero
  1498.  
  1499. (defun exp-dec (hold halfdec length)
  1500.   (let* ((target (expt 0.5 (/ length halfdec)))
  1501.      (expenv (pwev 1 hold 1 length target)))
  1502.     expenv)
  1503. )
  1504.  
  1505. ;;; operations on sounds
  1506.  
  1507. (defun diff (x y) (sum x (prod -1 y)))
  1508.  
  1509. ; compare-shape is a shape table -- origin 1.
  1510. (defun compare (x y &optional (compare-shape *step-shape*))
  1511.   (let ((xydiff (diff x y)))
  1512.     (shape xydiff compare-shape 1)))
  1513.  
  1514. ;;; oscs
  1515.  
  1516. (defun osc-saw (hz) (hzosc hz *saw-table*))
  1517. (defun osc-tri (hz) (hzosc hz *tri-table*))
  1518.  
  1519. ; bias is [-1, 1] pulse width.  sound or scalar.
  1520. ; hz is a sound or scalar
  1521. (defun osc-pulse (hz bias &optional (compare-shape *step-shape*))
  1522.   (compare bias (osc-tri hz) compare-shape))
  1523.  
  1524. (setf NY:ALL 1000000000)
  1525.